package portfelo.control;


import java.io.*;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import portfelo.db.QueryDB;
import portfelo.dto.AccountDto;
import portfelo.dto.PhotoDto;
import portfelo.dto.TagDto;

public class Control2 {
	//query with the queryDB
	private QueryDB query = null;
	
	public void init(ServletConfig config)
	{
		query = new QueryDB();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		if(query == null)
			query = new QueryDB();
		
		String action = request.getParameter("action");
		PhotoDto image = null;
		if(action.equals("up") || action.equals("down"))
			tagAction(action, null);
		else if(action.equals("settag"))
			tagAction(action, request.getParameter("selectedtag"));
		else if(action.equals("left") || action.equals("right"))
			image = photoAction(action);
		
//		private List<TagDto> tags; //list of tags for the current image
//		private PhotoDto currentImage; //currently selected image
//		private TagDto currentTag; //currently selected tag
//		private List<PhotoDto> tagImages; //List of images with the current tag
		

		
		List<TagDto> tags = query.getTags();
		PhotoDto currentImage = query.getCurrentImage();
		TagDto currentTag = query.getCurrentTag();
		List<PhotoDto> tagImages = query.getCurrentTagImages();
		
		TagDto tagList[] = new TagDto[tags.size()];
		for(int i = 0; i < tags.size(); i++)
		{
			tagList[i] = tags.get(i);
		}
		PhotoDto imageList[] = new PhotoDto[tagImages.size()];
		for(int i = 0; i < tagImages.size(); i++)
		{
			imageList[i] = tagImages.get(i);
		}
		
//		request.setAttribute("name", "value");
//		request.getRequestDispatcher("page.jsp").forward(request, response);

		request.setAttribute("currentTag", currentTag);
		request.setAttribute("tagList", tagList);
		request.setAttribute("currentImage", currentImage);
		request.setAttribute("imageList", imageList);
		
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		doGet(request,response);
	}
	
	//maybe not necessary
	public void destroy()
	{
		query.close();
	}
	
	private void tagAction(String action, String setTag)
	{
		if(action.equals("up"))
		{
			query.setNextTag();
		}
		else if(action.equals("down"))
		{
			query.setPreviousTag();
		}
		else if(action.equals("settag"))
		{
			query.setTag(setTag);
		}
	}
	
	private PhotoDto photoAction(String action)
	{
		PhotoDto ret = null;
		if(action.equals("left"))
			ret = query.getPreviousImage();
		else if(action.equals("right"))
			ret = query.getNextImage();
		
		return ret;
	}
}
